package com.hmdp.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdworker {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private static final int COUNT_BITS=32;
    private static final long BEGIN_TIMESTAMP=1640995200;
    public long nextID(String keyPrefix){
//        生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long epochSecond = now.toEpochSecond(ZoneOffset.UTC);
        long dataStamp=epochSecond-BEGIN_TIMESTAMP;
        String data = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        long increment = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + "：" + data );
        return dataStamp<<COUNT_BITS|increment;


    }

    public static void main(String[] args) {
        LocalDateTime time=LocalDateTime.of(2022,1,1,0,0);
        long second=time.toEpochSecond(ZoneOffset.UTC);
        System.out.println(second);
    }

}
